package org.px.gui;

import com.toedter.calendar.JDateChooser;
import org.px.domain.LeaveRecord;
import org.px.service.LeaveRecordService;
import org.px.domain.UserIdentity;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class AdminMainFrame extends JFrame {
    private UserIdentity user;
    private LeaveRecordService leaveRecordService = new LeaveRecordService();
    private DefaultTableModel tableModel;
    private JTable leaveTable;
    private JComboBox<String> statusCombo;
    private JPanel mainPanel; // 主面板
    private JPanel leaveRecordPanel;
    private JButton approveBtn; // 批准按钮
    private JButton rejectBtn;  // 拒绝按钮

    public AdminMainFrame(UserIdentity user) {
        this.user = user;
        initUI();
        setVisible(true);
    }

    private void initUI() {
        setTitle("员工请假管理系统 - 管理员主界面");
        setSize(1600, 1000);  // 增大窗口尺寸以适应表格
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        
        // 功能菜单保持不变
        JMenu functionMenu = new JMenu("功能");
        JMenuItem viewAllItem = new JMenuItem("查看所有请假记录");
        JMenuItem viewDeptLeaveItem = new JMenuItem("查看各部门的请假情况");
        // 新增按员工ID查询菜单项
        JMenuItem viewEmpLeaveItem = new JMenuItem("按员工ID查询请假情况");
        
        functionMenu.add(viewAllItem);
        functionMenu.add(viewDeptLeaveItem);
        functionMenu.add(viewEmpLeaveItem); // 添加新菜单项
        
        // 系统菜单
        JMenu systemMenu = new JMenu("系统");
        JMenuItem exitItem = new JMenuItem("退出");
        systemMenu.add(exitItem);
        
        menuBar.add(functionMenu);
        menuBar.add(Box.createHorizontalGlue()); // 将系统菜单推到右侧
        menuBar.add(systemMenu);
        
        // 设置菜单栏到窗体
        setJMenuBar(menuBar);

        // 创建主面板（使用BorderLayout）
        mainPanel = new JPanel(new BorderLayout());
        setContentPane(mainPanel); // 设置内容面板
        
        // 创建并保存请假记录界面面板
        leaveRecordPanel = createLeaveRecordPanel();
        mainPanel.add(leaveRecordPanel, BorderLayout.CENTER);

        // 初始化加载数据
        viewAllLeaveRecords();

        // 事件监听迁移到菜单项
        viewAllItem.addActionListener(e -> viewAllLeaveRecords());
        viewDeptLeaveItem.addActionListener(e -> viewDepartmentLeaveStatistics());
        viewEmpLeaveItem.addActionListener(e -> viewLeaveRecordsByEmpId());
        exitItem.addActionListener(e -> System.exit(0)); // 添加退出系统功能
    }

    //查看所有请假记录功能
    private void viewAllLeaveRecords() {
        try {
            String selectedStatus = (String) statusCombo.getSelectedItem();
            List<LeaveRecord> leaveRecords;
            if ("全部".equals(selectedStatus)) {
                leaveRecords = leaveRecordService.getAllLeaveRecords();
            } else {
                // 将中文状态转换为数据库中的状态值
                String status = convertStatus(selectedStatus);
                leaveRecords = leaveRecordService.getLeaveRecordsByStatus(status);
            }
            // 更新表格
            updateTableModel(leaveRecords);
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    //更新表格模型
    private void updateTableModel(List<LeaveRecord> records) {
        tableModel.setRowCount(0); // 清空表格
        for (LeaveRecord record : records) {
            Object[] rowData = {
                    record.getLeave_id(),
                    record.getEmp_id(),
                    record.getLeave_type(),
                    record.getStart_time(),
                    record.getEnd_time(),
                    record.getDuration(),
                    record.getReason(),
                    record.getApprover_id(),
                    record.getStatus(),
                    record.getApply_time()
            };
            tableModel.addRow(rowData);
        }
    }

    //将中文状态转换为数据库状态
    private String convertStatus(String chineseStatus) {
        switch (chineseStatus) {
            case "待审批": return "待审批";
            case "已批准": return "已批准";
            case "已拒绝": return "已拒绝";
            default: return "";
        }
    }

    //查看各部门请假情况
    private void viewDepartmentLeaveStatistics() {
        // 清空主面板
        mainPanel.removeAll();
        mainPanel.setLayout(new BorderLayout());
        
        // 创建顶部面板（日期选择和查询按钮）
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel dateLabel = new JLabel("选择日期:");
        JDateChooser dateChooser = new JDateChooser();
        dateChooser.setDateFormatString("yyyy-MM-dd");
        JButton queryBtn = new JButton("查询");
        topPanel.add(dateLabel);
        topPanel.add(dateChooser);
        topPanel.add(queryBtn);
        
        // 新增返回按钮
        JButton backButton = new JButton("返回请假记录");
        backButton.addActionListener(e -> {
            mainPanel.removeAll();
            mainPanel.add(leaveRecordPanel, BorderLayout.CENTER);
            mainPanel.revalidate();
            mainPanel.repaint();
            viewAllLeaveRecords(); // 刷新数据
        });
        topPanel.add(backButton);
        
        mainPanel.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"部门名称", "请假人数"};
        DefaultTableModel deptModel = new DefaultTableModel(columnNames, 0);
        JTable deptTable = new JTable(deptModel);
        deptTable.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        deptTable.setRowHeight(30);
        JScrollPane scrollPane = new JScrollPane(deptTable);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 查询按钮事件处理
        queryBtn.addActionListener(e -> {
            java.util.Date selectedDate = dateChooser.getDate();
            if (selectedDate == null) {
                JOptionPane.showMessageDialog(this, "请选择日期", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            try {
                List<Map<String, Object>> stats = leaveRecordService.getDepartmentLeaveStatistics(selectedDate);
                deptModel.setRowCount(0); // 清空表格
                for (Map<String, Object> row : stats) {
                    Object[] rowData = {
                        row.get("dept_name"),
                        row.get("leave_count")
                    };
                    deptModel.addRow(rowData);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 刷新界面
        mainPanel.revalidate();
        mainPanel.repaint();
    }

    //创建请假记录界面面板
    private JPanel createLeaveRecordPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        
        // 创建顶部筛选面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        filterPanel.add(new JLabel("状态筛选:"));
        statusCombo = new JComboBox<>(new String[]{"全部", "待审批", "已批准", "已拒绝"});
        filterPanel.add(statusCombo);
        
        // 添加筛选按钮
        JButton filterBtn = new JButton("筛选");
        filterBtn.addActionListener(e -> viewAllLeaveRecords());
        filterPanel.add(filterBtn);
        
        panel.add(filterPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"请假ID", "员工ID", "请假类型", "开始时间", "结束时间", "天数", "原因", "审批人ID", "状态", "申请时间"};
        tableModel = new DefaultTableModel(columnNames, 0);
        leaveTable = new JTable(tableModel);
        // 设置表格字体（放大到24号）
        leaveTable.setFont(new Font("微软雅黑", Font.PLAIN, 24));  // 修改字体大小
        leaveTable.setRowHeight(30);
        panel.add(new JScrollPane(leaveTable), BorderLayout.CENTER);
        
        // 新增按钮面板
        JPanel buttonPanel = new JPanel();
        approveBtn = new JButton("批准");
        approveBtn.addActionListener(e -> approveSelectedLeave());
        rejectBtn = new JButton("拒绝");
        rejectBtn.addActionListener(e -> rejectSelectedLeave());
        buttonPanel.add(approveBtn);
        buttonPanel.add(rejectBtn);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        
        return panel;
    }

    // 批准选中的请假记录
    private void approveSelectedLeave() {
        int selectedRow = leaveTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要批准的假条", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int leaveId = (int) leaveTable.getValueAt(selectedRow, 0); // 请假ID在第0列
        String status = (String) leaveTable.getValueAt(selectedRow, 8); // 状态在第8列
        
        // 新增：检查假条状态，如果是已审批状态则要求确认
        if (!"待审批".equals(status)) {
            // 创建确认面板
            JPanel confirmPanel = new JPanel(new BorderLayout(5,5));
            confirmPanel.add(new JLabel("确定对已经审批的假条进行重新审批？"), BorderLayout.NORTH);
            
            JPanel inputPanel = new JPanel();
            inputPanel.add(new JLabel("管理员ID:"));
            JTextField adminIdField = new JTextField(15);
            inputPanel.add(adminIdField);
            confirmPanel.add(inputPanel, BorderLayout.CENTER);
            
            int result = JOptionPane.showConfirmDialog(
                this,
                confirmPanel,
                "重新审批确认",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE
            );
            
            if (result == JOptionPane.OK_OPTION) {
                String inputId = adminIdField.getText().trim();
                if (!inputId.equals(user.getUser_id())) {
                    JOptionPane.showMessageDialog(this, "管理员ID验证失败", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                return; // 用户取消操作
            }
        }
        
        try {
            if (leaveRecordService.updateLeaveRecordStatus(leaveId, "已批准", user.getUser_id())) {
                JOptionPane.showMessageDialog(this, "批准成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                viewAllLeaveRecords(); // 刷新表格
            } else {
                JOptionPane.showMessageDialog(this, "批准失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 拒绝选中的请假记录
    private void rejectSelectedLeave() {
        int selectedRow = leaveTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要拒绝的假条", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int leaveId = (int) leaveTable.getValueAt(selectedRow, 0); // 请假ID在第0列
        String status = (String) leaveTable.getValueAt(selectedRow, 8); // 状态在第8列
        
        // 新增：检查假条状态，如果是已审批状态则要求确认
        if (!"待审批".equals(status)) {
            // 创建确认面板
            JPanel confirmPanel = new JPanel(new BorderLayout(5,5));
            confirmPanel.add(new JLabel("确定对已经审批的假条进行重新审批？"), BorderLayout.NORTH);
            
            JPanel inputPanel = new JPanel();
            inputPanel.add(new JLabel("管理员ID:"));
            JTextField adminIdField = new JTextField(15);
            inputPanel.add(adminIdField);
            confirmPanel.add(inputPanel, BorderLayout.CENTER);
            
            int result = JOptionPane.showConfirmDialog(
                this,
                confirmPanel,
                "重新审批确认",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE
            );
            
            if (result == JOptionPane.OK_OPTION) {
                String inputId = adminIdField.getText().trim();
                if (!inputId.equals(user.getUser_id())) {
                    JOptionPane.showMessageDialog(this, "管理员ID验证失败", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                return; // 用户取消操作
            }
        }
        
        try {
            if (leaveRecordService.updateLeaveRecordStatus(leaveId, "已拒绝", user.getUser_id())) {
                JOptionPane.showMessageDialog(this, "拒绝成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                viewAllLeaveRecords(); // 刷新表格
            } else {
                JOptionPane.showMessageDialog(this, "拒绝失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    // 新增：按员工ID查询请假记录
    private void viewLeaveRecordsByEmpId() {
        // 弹出输入对话框获取员工ID
        String empId = JOptionPane.showInputDialog(this, "请输入员工ID:");
        if (empId == null || empId.trim().isEmpty()) {
            return; // 用户取消或输入为空
        }
        
        // 清空主面板
        mainPanel.removeAll();
        mainPanel.setLayout(new BorderLayout());
        
        // 创建顶部面板（包含返回按钮）
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton backButton = new JButton("返回所有请假记录");
        backButton.addActionListener(e -> {
            mainPanel.removeAll();
            mainPanel.add(leaveRecordPanel, BorderLayout.CENTER);
            mainPanel.revalidate();
            mainPanel.repaint();
            viewAllLeaveRecords(); // 刷新数据
        });
        topPanel.add(backButton);
        mainPanel.add(topPanel, BorderLayout.NORTH);
        
        try {
            // 获取员工请假记录
            List<LeaveRecord> records = leaveRecordService.getLeaveRecordsByEmpId(empId);
            
            // 新增：检查查询结果是否为空
            if (records.isEmpty()) {
                JOptionPane.showMessageDialog(this, "该员工不存在或没有请假记录", "提示", JOptionPane.INFORMATION_MESSAGE);
                mainPanel.removeAll();
                mainPanel.add(leaveRecordPanel, BorderLayout.CENTER);
                mainPanel.revalidate();
                mainPanel.repaint();
                return;
            }
            
            // 创建表格
            String[] columnNames = {"请假ID", "员工ID", "请假类型", "开始时间", "结束时间", "天数", "原因", "审批人ID", "状态", "申请时间"};
            DefaultTableModel empModel = new DefaultTableModel(columnNames, 0);
            JTable empTable = new JTable(empModel);
            empTable.setFont(new Font("微软雅黑", Font.PLAIN, 24));
            empTable.setRowHeight(30);
            JScrollPane scrollPane = new JScrollPane(empTable);
            mainPanel.add(scrollPane, BorderLayout.CENTER);
            
            // 添加审批按钮面板
            JPanel buttonPanel = new JPanel();
            JButton approveBtn = new JButton("批准");
            approveBtn.addActionListener(e -> approveSelectedLeave(empTable));
            JButton rejectBtn = new JButton("拒绝");
            rejectBtn.addActionListener(e -> rejectSelectedLeave(empTable));
            buttonPanel.add(approveBtn);
            buttonPanel.add(rejectBtn);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);
            
            // 填充表格数据
            for (LeaveRecord record : records) {
                Object[] rowData = {
                    record.getLeave_id(),
                    record.getEmp_id(),
                    record.getLeave_type(),
                    record.getStart_time(),
                    record.getEnd_time(),
                    record.getDuration(),
                    record.getReason(),
                    record.getApprover_id(),
                    record.getStatus(),
                    record.getApply_time()
                };
                empModel.addRow(rowData);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(),
                "系统错误", JOptionPane.ERROR_MESSAGE);
        }
        
        // 刷新界面
        mainPanel.revalidate();
        mainPanel.repaint();
    }
    
    // 修改后的批准方法（支持传入表格参数）
    private void approveSelectedLeave(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要批准的假条", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int leaveId = (int) table.getValueAt(selectedRow, 0); // 请假ID在第0列
        String status = (String) table.getValueAt(selectedRow, 8); // 状态在第8列
        
        // 新增：检查假条状态，如果是已审批状态则要求确认
        if (!"待审批".equals(status)) {
            // 创建确认面板
            JPanel confirmPanel = new JPanel(new BorderLayout(5,5));
            confirmPanel.add(new JLabel("确定对已经审批的假条进行重新审批？"), BorderLayout.NORTH);
            
            JPanel inputPanel = new JPanel();
            inputPanel.add(new JLabel("管理员ID:"));
            JTextField adminIdField = new JTextField(15);
            inputPanel.add(adminIdField);
            confirmPanel.add(inputPanel, BorderLayout.CENTER);
            
            int result = JOptionPane.showConfirmDialog(
                this,
                confirmPanel,
                "重新审批确认",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE
            );
            
            if (result == JOptionPane.OK_OPTION) {
                String inputId = adminIdField.getText().trim();
                if (!inputId.equals(user.getUser_id())) {
                    JOptionPane.showMessageDialog(this, "管理员ID验证失败", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                return; // 用户取消操作
            }
        }
        
        try {
            if (leaveRecordService.updateLeaveRecordStatus(leaveId, "已批准", user.getUser_id())) {
                JOptionPane.showMessageDialog(this, "批准成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                viewAllLeaveRecords(); // 刷新表格
            } else {
                JOptionPane.showMessageDialog(this, "批准失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    // 修改后的拒绝方法（支持传入表格参数）
    private void rejectSelectedLeave(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要拒绝的假条", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int leaveId = (int) table.getValueAt(selectedRow, 0); // 请假ID在第0列
        String status = (String) table.getValueAt(selectedRow, 8); // 状态在第8列
        
        // 新增：检查假条状态，如果是已审批状态则要求确认
        if (!"待审批".equals(status)) {
            // 创建确认面板
            JPanel confirmPanel = new JPanel(new BorderLayout(5,5));
            confirmPanel.add(new JLabel("确定对已经审批的假条进行重新审批？"), BorderLayout.NORTH);
            
            JPanel inputPanel = new JPanel();
            inputPanel.add(new JLabel("管理员ID:"));
            JTextField adminIdField = new JTextField(15);
            inputPanel.add(adminIdField);
            confirmPanel.add(inputPanel, BorderLayout.CENTER);
            
            int result = JOptionPane.showConfirmDialog(
                this,
                confirmPanel,
                "重新审批确认",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE
            );
            
            if (result == JOptionPane.OK_OPTION) {
                String inputId = adminIdField.getText().trim();
                if (!inputId.equals(user.getUser_id())) {
                    JOptionPane.showMessageDialog(this, "管理员ID验证失败", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                return; // 用户取消操作
            }
        }
        
        try {
            if (leaveRecordService.updateLeaveRecordStatus(leaveId, "已拒绝", user.getUser_id())) {
                JOptionPane.showMessageDialog(this, "拒绝成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                viewAllLeaveRecords(); // 刷新表格
            } else {
                JOptionPane.showMessageDialog(this, "拒绝失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
